/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.universalvideoviewsample.slice;


import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.bundle.AbilityInfo;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

import com.mylibrary.player.HmPlayer;
import com.mylibrary.player.api.ImplPlayer;
import com.mylibrary.player.api.StatuChangeListener;
import com.mylibrary.player.constant.Constants;
import com.mylibrary.player.constant.PlayerStatu;
import com.mylibrary.player.util.CommonUtils;
import com.mylibrary.player.view.UniversalVideoView;
import com.mylibrary.player.view.UniversalMediaController;
import com.universalvideoviewsample.ResourceTable;

/**
 * MainAbilitySlice
 */
public class MainAbilitySlice extends AbilitySlice {
    private ImplPlayer player;
    private DirectionalLayout parentLayout;
    private DependentLayout videoViewLayout;
    private DirectionalLayout bottomLayout;
    private UniversalVideoView universalVideoView;
    private UniversalMediaController controllerView;
    private static final String URL = "https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/cae-legoup-video-target/93be3d88-9fc2-4fbd-bd14-833bca731ca7.mp4";
    private int videoViewHeight;
    private AbilityInfo.DisplayOrientation currentDisplayOrientation;
    private long startEndTime;

    EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner()){
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            Window window = getWindow();
            if(window != null){
                if (event.eventId == 0) {
                    window.addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);
                } else if (event.eventId == 1) {
                    window.clearFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);
                }
            }

        }
    };
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        player = new HmPlayer.Builder(this).setFilePath(URL).create();
        player.getLifecycle().onStart();
        initComponent();

    }

    private void initComponent() {
        if (findComponentById(ResourceTable.Id_parent) instanceof DirectionalLayout) {
            parentLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_parent);
        }
        if (findComponentById(ResourceTable.Id_video_layout) instanceof DependentLayout) {
            videoViewLayout = (DependentLayout) findComponentById(ResourceTable.Id_video_layout);
        }
        if (findComponentById(ResourceTable.Id_bottom_layout) instanceof DirectionalLayout) {
            bottomLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_bottom_layout);
        }
        if (findComponentById(ResourceTable.Id_player_view) instanceof UniversalVideoView) {
            universalVideoView = (UniversalVideoView) findComponentById(ResourceTable.Id_player_view);
        }
        if (findComponentById(ResourceTable.Id_controller_view) instanceof UniversalMediaController) {
            controllerView = (UniversalMediaController) findComponentById(ResourceTable.Id_controller_view);
        }
        Button startBtn = (Button) findComponentById(ResourceTable.Id_start);
        startBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                long currentTime = System.currentTimeMillis();
                if(Math.abs(currentTime - startEndTime) < 1000){
                    return;
                }
                controllerView.setTitle("Video Name");
                getGlobalTaskDispatcher(TaskPriority.DEFAULT).delayDispatch(() -> player.memoryPlay(true), Constants.NUMBER_1000);
                startEndTime = System.currentTimeMillis();
            }
        });
        universalVideoView.bind(player);
        universalVideoView.setMediaController(controllerView);
        controllerView.showTileAndBottomControl(false);
        controllerView.bind(player);
        player.addPlayerStatuCallback(new StatuChangeListener() {
            @Override
            public void statuCallback(PlayerStatu statu) {
                if (statu == PlayerStatu.PLAY) {
                    mHandler.sendEvent(0);
                } else if (statu == PlayerStatu.COMPLETE) {
                    mHandler.sendEvent(1, 1000);
                }else if(statu == PlayerStatu.PAUSE){
                    mHandler.sendEvent(1, 1000);
                }
            }
        });

    }

    @Override
    protected void onBackPressed() {
        if (currentDisplayOrientation != null && currentDisplayOrientation.ordinal() ==  AbilityInfo.DisplayOrientation.LANDSCAPE.ordinal()) {
            controllerView.setFullScreen(false, AbilityInfo.DisplayOrientation.PORTRAIT.ordinal());
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        currentDisplayOrientation = displayOrientation;
        controllerView.updateOrientationIcon(displayOrientation.ordinal());
        if (videoViewHeight == 0) {
            videoViewHeight = videoViewLayout.getLayoutConfig().height;
        }
        int screenWidth = CommonUtils.getScreenWidth(this);
        parentLayout.setWidth(screenWidth);
        if (displayOrientation == AbilityInfo.DisplayOrientation.LANDSCAPE) {
            DirectionalLayout.LayoutConfig layoutConfig = (DirectionalLayout.LayoutConfig) videoViewLayout.getLayoutConfig();
            layoutConfig.width = DependentLayout.LayoutConfig.MATCH_PARENT;
            layoutConfig.height = DependentLayout.LayoutConfig.MATCH_PARENT;
            videoViewLayout.setLayoutConfig(layoutConfig);
            bottomLayout.setVisibility(Component.HIDE);
        } else {
            DirectionalLayout.LayoutConfig layoutConfig = (DirectionalLayout.LayoutConfig) videoViewLayout.getLayoutConfig();
            layoutConfig.width = DependentLayout.LayoutConfig.MATCH_PARENT;
            layoutConfig.height = videoViewHeight;
            videoViewLayout.setLayoutConfig(layoutConfig);
            bottomLayout.setVisibility(Component.VISIBLE);
        }

    }

    @Override
    public void onActive() {
        super.onActive();
        controllerView.updatePlayToogleButtonState();
    }

    @Override
    public void onForeground(Intent intent) {
        player.getLifecycle().onForeground();
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        player.getLifecycle().onBackground();
        super.onBackground();
    }

    @Override
    protected void onStop() {
        controllerView.unbind();
        universalVideoView.unbind();
        player.getLifecycle().onStop();
        super.onStop();
    }
}
